#!/usr/bin/env python3
# coding:utf-8

""" 
实现一个类似 repo 的功能, 自动clone 并 pull 子模块
"""

import os
from dataclasses import dataclass


@dataclass
class git_submodule:
    name: str
    url: str
    back_url: str
    path: str


pb_depend_git_submodule = [
    git_submodule(
        "7_ros-robot-example",
        "git@gitee.com:zero2200/7_ros-robot-example.git",
        "7_ros-robot-example",
        "ros_example",
    ),
    git_submodule(
        "2_C_example",
        "git@gitee.com:zero2200/2_C_example.git",
        "https://gitee.com/zero2200/2_C_example.git",
        "example/c_example",
    ),
]


class Sync_Git_Submodule:
    def __init__(self, git_list):
        self.git_list = git_list

    def git_init(self, url, back_url, path):
        work_dir = os.getcwd()
        if not os.path.exists(path):
            os.makedirs(path)
        os.chdir(path)
        cmd = f"git clone {url}"
        ret = os.system(cmd)
        if ret != 0:
            cmd = f"git clone {back_url}"
            ret = os.system(cmd)
            if ret != 0:
                raise Exception(f"git clone ${url} 失败,请检查网络, 与 git url")
        os.chdir(work_dir)

    def git_sync(self, url, path):
        work_dir = os.getcwd()
        os.chdir(path)
        cmd = f"git pull"
        ret = os.system(cmd)
        if ret != 0:
            print(f"git pull ${url} 失败,请检查网络, 与 git url")
            # raise Exception(f"git pull ${url} 失败,请检查网络, 与 git url")
        os.chdir(work_dir)

    def sync(self):
        for item in self.git_list:
            git_full_dir = item.path + "/" + item.name
            if not os.path.exists(f"{git_full_dir}/.git"):
                self.git_init(item.url, item.back_url, item.path)
            self.git_sync(item.url, git_full_dir)


if __name__ == "__main__":
    git_manage = Sync_Git_Submodule(pb_depend_git_submodule)
    git_manage.sync()


""" 运行结果: python3 7_git_submodule_自动clone_pull.py

ls example/ ros_example/
example/:
c_example

ros_example/:
7_ros-robot-example
"""